import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,

  Checkbox, DatePicker, Alert, Tooltip,
} from 'antd';
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import request from '@/utils/request';
import './index.less'
import {download, formateObjToParamStr2, getEW} from "@/utils/utils";
import config from "@/config/config";
import {routerRedux} from "dva/router";
import AreaMap from "@/components/AreaMap";

const FormItem = Form.Item;

@connect(({staff_report, loading, global}) => ({
  staff_report,
  global,
  loading: loading.models.staff_report,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'device_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'device_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      maxWidth: 200,
      all_users: [],
    };

  }


  componentDidMount() {

    const {dispatch} = this.props;
    const {
      staff_report: {pageLoaded, scrollData},
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.ant-table-body');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        staff_report: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'staff_report/changeTableY',
      });
      dispatch({
        type: 'staff_report/fetch',
        payload: searchParams,
        callback: () => {
          const {dispatch} = this.props;
          dispatch({
            type: 'staff_report/changeLoaded',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    this.setState({
      maxWidth: document.querySelector('.table-page').offsetWidth - 20
    }, function () {
      console.log('maxWidth', this.state.maxWidth)
    })


    const that = this;
    request(`/revenue_statistics_users`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_users: response.data.data
        })
      }

    });

  }

  scroll = (e) => {
    console.log('scroll');
    const {dispatch} = this.props;
    dispatch({
      type: 'staff_report/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const {dispatch} = this.props;

    dispatch({
      type: 'staff_report/changeTableY',
    });
  };


  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'staff_report/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };
  handleExport = () => {
    const {
      staff_report: {searchParams},
    } = this.props;
    console.log('searchParams', searchParams);
    download(`${config.prefix}/user_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr2(({...searchParams,
      company_ids:getEW(searchParams.company_ids)}))}`);

  };

  renderSimpleForm() {
    const {
      staff_report: {searchParams},
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label={'员工名称'}>
          {getFieldDecorator('user_ids', {
            initialValue: searchParams.user_ids,
          })(
            <Checkbox.Group style={{width: '100%'}}>
              {
                this.state.all_users.map((item, index) => {
                  return <Checkbox key={index} value={item.id}>{item.username}</Checkbox>
                })
              }

            </Checkbox.Group>
          )}
        </FormItem>
        <br/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const {form} = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log(fieldsValue)
                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
                  end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {/* <Button type={'primary'} className={'btn-cyan'} style={{ marginLeft: 8 }} icon='export' onClick={()=>{message.info('功能正在开发中')}}>
            导出报表
          </Button> */}
          {
            find(this.permissions, {name: 'user_report_export'}) &&
            <Tooltip title={'请先查询一次再导出'}>
              <Button
                className={'btn-green'}
                type="primary"
                icon="export"
                onClick={this.handleExport}
                style={{marginLeft: '10px'}}
              >导出报表
              </Button>
            </Tooltip>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    this.props.dispatch({
      type: 'staff_report/add',
      payload: {
        ...formValues,
      },
      callback() {
        message.success('新建设备成功');
        that.setState({
          addModal: false,
        });
        const {
          staff_report: {searchParams},
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      company_ids:sessionStorage.getItem('company_sign'),
      company_id:'',
      user_ids: [],
      start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', "YYYY-MM-DD").format("YYYY-MM-DD"),
      end_date: moment(new Date()).format('YYYY-MM-DD'),
      page: 1,
      per_page: 30,
    });
  };

  handleClick = (key, date, row) => {
    console.log('key)', key);
    const {panes, routerMapping} = this.props.global;
    const {dispatch} = this.props;
    const activeKey = key;
    const that = this;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    console.log('row', row)
    const {
      staff_report: {searchParams},
    } = this.props;
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
      callback: function () {
        const sendSearchParams = {
          start_date: date !== '合计' ? date : searchParams.start_date,
          end_date: date !== '合计' ? date : searchParams.end_date,
          region_id: "",
          name: '',
          mobile: '',
          date_type: "generation_date",
          meter_number: '',
          operator_name: '',
          type: '',
          invoicing_status: '',
          page: 1,
          per_page: 50,
          id: '',
          operator_id: row.user_id ? row.user_id : ''
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'payment/changeLoadedFalse',
          callback: function () {
            dispatch({
              type: 'payment/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

      }
    });
  };
  handleClickOwner = (key, date, row) => {
    console.log('key)', key);
    const {panes, routerMapping} = this.props.global;
    const {dispatch} = this.props;
    const activeKey = key;
    const that = this;
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      panes.push({
        title: find(routerMapping, o => o.path == activeKey).name,
        content: 'New Tab Pane',
        key: activeKey,
      });
    }
    dispatch(routerRedux.push(activeKey));
    console.log('row', row)
    const {
      staff_report: {searchParams},
    } = this.props;
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
      callback: function () {
        const sendSearchParams = {
          start_date: date !== '合计' ? date : searchParams.start_date,
          end_date: date !== '合计' ? date : searchParams.end_date,
          region_id: "",
          region_name: '',
          vendor_id: '',
          account_nature: '',
          status: '0',
          balance_status: '0',
          caliber: '',
          price_nature_id: '',
          name: '',
          mobile: '',
          meter_number: '',
          address: '',
          filter_level: '',
          filter_year: '',
          page: 1,
          per_page: 50,
          operator_id: row.user_id ? row.user_id : ''
        };
        console.log('sendSearchParams', sendSearchParams);
        dispatch({
          type: 'owner/changeLoadedFalse',
          callback: function () {
            dispatch({
              type: 'owner/changeSearchParams',
              payload: sendSearchParams,
            });
          }
        });

      }
    });
  };

  render() {
    const that = this;
    const {
      staff_report: {data, loading, tableY, meta, summary, selectedRowKeys, additional},
      global: {gridTableW}
    } = this.props;
    const columns = [
      {
        title: '日期',
        dataIndex: 'date',
        width: 100,
        fixed: 'left'
      },
    ];
    let tableX = 100
    if (data[0] && data[0].items) {
      for (let i = 0; i < data[0].items.length; i++) {
        let name = data[0].items[i].username
        columns.push({
          title: name,
          className: `vendor-meter${i % 4 + 1}`,
          children: [
            {
              title: '开户数',
              dataIndex: `total_count${i + 1}`,
              width: 70,
              className: `vendor-meter${i % 4 + 1}`,
              // render: (text, record) => {
              //   const findByName = find(record.items, (o) => o.username === name)
              //   return findByName ? findByName.open_account_count : ''
              // },
              render: (text, record) => {
                const findByName = find(record.items, (o) => o.username === name)
                const canclick = (find(that.permissions, {name: 'owner_information'})) && (findByName.username !== '汇总')
                return <span style={{
                  color: 'blue',
                  cursor: 'pointer'
                }} onClick={() => {
                  this.handleClickOwner('/owner', record.date, findByName?findByName:{})
                }}>{findByName ? findByName.open_account_count : ''}</span>
              }
            },
            {
              title: '收费笔数',
              dataIndex: `normal_count${i + 1}`,
              className: `vendor-meter${i % 4 + 1}`,
              width: 75,
              render: (text, record) => {
                const findByName = find(record.items, (o) => o.username === name)
                const canclick = (find(that.permissions, {name: 'payment_record'}))
                return <span style={{
                  color: 'blue',
                  cursor: 'pointer'
                }} onClick={() => {
                  this.handleClick('/payment', record.date, findByName ? findByName : {})
                }}>{findByName ? findByName.charge_count : ''}</span>
              }
            },
            {
              title: '收费金额',
              dataIndex: `abnormality_count${i + 1}`,
              className: `vendor-meter${i % 4 + 1}`,
              width: 75,
              render: (text, record) => {
                const findByName = find(record.items, (o) => o.username === name)
                return findByName ? Number(findByName.charge_amount).toFixed(2) : ''
              }
            },
          ]
        },)
      }
      tableX = 100 + (data[0].items.length * 230)
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>员工报表</span>
      </div>
      <div className="table-page">
        <div className="table-condition">
          {this.renderSimpleForm()}
        </div>
        <div>
          <Table
            style={{color: '#fff', maxWidth: this.state.maxWidth + 'px'}}
            className="custom-small-table meter-table vendor-meter staff-report"
            loading={loading}
            rowKey={'date'}
            dataSource={[...data].reverse()}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{x: tableX, y: tableY}}
          />
        </div>


      </div>
    </div>;
  }
}

export default BasicList;
